﻿using Restful_Api.Entities;
using Restful_Api.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Restful_Api.Services
{   
    public class PropertyMappingService: IPropertyMappingService
    {
        private Dictionary<string, PropertMappingValue> _emplpyeePropertyMapping =
            new Dictionary<string, PropertMappingValue>(StringComparer.OrdinalIgnoreCase) {
                { "Id",new PropertMappingValue(new List<string>{"id"}) },
                { "CompanyId",new PropertMappingValue(new List<string>{"CompanyId"}) },
                { "EmployeeNo",new PropertMappingValue(new List<string>{"EmployeeNo"}) },
                { "Name",new PropertMappingValue(new List<string>{ "FistName", "LastName"}) },
                { "GenderDisplay",new PropertMappingValue(new List<string>{"Gender"}) },
                { "Age",new PropertMappingValue(new List<string>{"DateOfBirth"},true) }
            };

        private Dictionary<string, PropertMappingValue> _companyPropertyMapping =
        new Dictionary<string, PropertMappingValue>(StringComparer.OrdinalIgnoreCase) {
                { "Id",new PropertMappingValue(new List<string>{"id"}) },
                { "CompanyName",new PropertMappingValue(new List<string>{"Name"}) },
                { "Country",new PropertMappingValue(new List<string>{"Country"}) },
                { "Industry",new PropertMappingValue(new List<string>{ "Industry"}) },
                { "Product",new PropertMappingValue(new List<string>{"Product"}) },
                { "Introduction",new PropertMappingValue(new List<string>{"Introduction"},true) }
        };

        private IList<IPropertyMapping> propertyMappings=new List<IPropertyMapping>();

        public PropertyMappingService()
        {
            propertyMappings.Add(new PropertyMapping<EmployeeDto, Employee>(_emplpyeePropertyMapping));
            propertyMappings.Add(new PropertyMapping<CompanyDto, Company>(_companyPropertyMapping));
        }

        public Dictionary<string, PropertMappingValue> GetPropertyMapping<TSource, TDstination>()
        {
            var matchingMapping = propertyMappings.OfType<PropertyMapping<TSource, TDstination>>().ToList();
            if (matchingMapping.Count == 1)
                return matchingMapping.First()._mappingDictionary;

            throw new Exception($"无法找到唯一的映射关系{typeof(TSource)},{typeof(TDstination)}");
        }
    }
}
